import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import store from './store';
// 创建 axios 实例
let httpClient: AxiosInstance;
httpClient = axios.create({
    baseURL: "", // api 的 base_url
    timeout: 50000 * 10 // 请求超时时间
});

// request 拦截器 axios 的一些配置
httpClient.interceptors.request.use(

    (config: AxiosRequestConfig) => {
        if (store.state.token) {
            config.headers.common['token'] = sessionStorage.getItem('token') ? sessionStorage.getItem('token') : ''
        }
        return config;
    },
    (error: any) => {
        console.error("error:", error);
        Promise.reject(error);
    }
);

// respone 拦截器 axios 的一些配置
httpClient.interceptors.response.use(
    (res: AxiosResponse) => {
        if (res.status === 200) {
            const data = res.data
            // 登入用户不存在
            if (data.code === 'S00A0002') {

            }
            return data;
        } else {
            return Promise.reject(new Error(res.data.msg || "Error"));
        }
    },
    (error) => {
        if (error.response.status === 401) {
            // 清除缓存
            store.commit('clearUserInfo')
        }
        if (error.response.status === 403) {
            return Promise.reject(new Error(error.response.data.message || "Error"));
        }
        return Promise.reject(error)
    }
);
export default httpClient;
